<template>
  <div class="bigbox">
    <el-form-item>
      <el-button type="warning" @click="addGoods">新增</el-button>
    </el-form-item>
  </div>
  <div>
    <el-table :data="tableData" stripe style="width: 100%" highlight-current-row
      :header-cell-style="{ background: 'rgb(179, 108, 255)', color: '#fff' }" max-height="650">
      <el-table-column align="center" prop="goodsname" label="商品名称" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="goodsdes" label="商品描述" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="price" label="商品单价" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="goodsnumber" label="商品库存" :show-overflow-tooltip="true" />
      <el-table-column align="center" prop="imageone" label="商品封面图">
        <template #default="scope">
          <el-image class="tableData_image" :src="scope.row.imageone"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300px">
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center">
            <el-button size="small" type="warning" @click="editGoods(scope.row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteGoods(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" @prev-click="getList()"
      @next-click="getList()" background v-model:page-size="pageSize" v-model:current-page="page"
      layout="prev, pager, next,sizes" :total="total" />

    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form ref="goodsForm" :model="form" :rules="rules" @submit.native.prevent="onSubmit">
        <el-form-item label="商品名称" prop="goodsname" :label-width="formLabelWidth">
          <el-input v-model="form.goodsname" autocomplete="on" />
        </el-form-item>
        <el-form-item label="商品描述" prop="goodsdes" :label-width="formLabelWidth">
          <el-input v-model="form.goodsdes" autocomplete="on" />
        </el-form-item>
        <el-form-item label="商品单价" prop="price" :label-width="formLabelWidth">
          <el-input v-model="form.price" autocomplete="on" type="number" />
        </el-form-item>
        <el-form-item label="商品库存" prop="goodsnumber" :label-width="formLabelWidth">
          <el-input v-model="form.goodsnumber" autocomplete="on" type="number" />
        </el-form-item>
        <el-form-item label="商品展示图" prop="bannerImage">
          <el-upload :headers="headers" class="upload_image" :http-request="uploadImage" :show-file-list="false">
            <el-image :src="form.imageone" v-if="form.imageone" class="bannerImage" />
            <el-icon :size="35" color="#a8abb2" v-else>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  goodsListApi,
  imageUpload,
  goodsDeleteApi,
  goodsDetailApi,
  goodsEditApi,
  goodsAddApi,
} from "../../api/index";
import { useRouter } from 'vue-router'
import { onMounted, ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
const router = useRouter()
// 响应式数据  
const tableData = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const dialogFormVisible = ref(false);
const title = ref('');
const form = ref({});
const formLabelWidth = 80;

// 验证规则  
const rules = {
  goodsname: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  goodsdes: [{ required: true, message: "商品描述不能为空", trigger: "blur" }],
  price: [{ required: true, message: "商品单价不能为空", trigger: "blur" }],
  goodsnumber: [{ required: true, message: "商品库存不能为空", trigger: "blur" }],
  imageone: [{ required: true, message: "商品展示图不能为空", trigger: "blur" }],
}
//这个是监听到一页展示多少条数据的控制监听函数
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
}
//这个是监听点击哪一页就跳转到哪一页的监听函数
const handleCurrentChange = (number) => {
  page.value = number;
  getList();
}
const uploadImage = (param) => {
  // 获取上传的文件名
  var file = param.file;
  //发送请求的参数格式为FormData
  const formData = new FormData();
  formData.append("file", file);
  // 调用param中的钩子函数处理各种情况，这样就可以用在组件中用钩子了。也可以用res.code==200来进行判断处理各种情况
  imageUpload(formData, param)
    .then((res) => {
      if (res.data.code == 1) {
        form.value.imageone = res.data.data.path;
      }
    })
    .catch((err) => {
      param.onError(err);
    });
}
const addGoods = () => {
  title.value = "新增商品";
  dialogFormVisible.value = true;
  form.value = {}
}

const getList = () => {
  goodsListApi({
    page: page.value,
    pageSize: pageSize.value,
  }).then((res) => {
    console.log(res);
    if (res.data.code == 1) {
      tableData.value = res.data.data;
      total.value = res.data.total;
    }
    if (res.data.code == 401) {
      ElMessage({
        type: "error",
        message: res.data.msg,
        duration: 1000,
        onClose: () => {
          router.replace("/login");
        },
      });
    }
  });
}
const deleteGoods = (id) => {
  goodsDeleteApi({ id: id }).then((res) => {
    if (res.data.code == 1) {
      ElMessage({
        type: "success",
        message: res.data.msg,
        duration: 1500,
        onClose: () => {
          getList();
        },
      });
    } else {
      ElMessage({
        type: "error",
        message: res.data.msg,
      });
    }
  });
}
const editGoods = (id) => {
  title.value = "修改商品信息";
  dialogFormVisible.value = true;
  goodsDetailApi(id).then((res) => {
    if (res.data.code == 1) {
      form.value = res.data.data;
    } else {
      ElMessage({
        type: "error",
        message: "获取数据失败",
      });
    }
  });
}
const goodsForm = ref(null)
const onSubmit = () => {
  goodsForm.value.validate((valid) => {
    if (valid) {
      if (form.value.id) {
        goodsEditApi(form.value).then((res) => {
          if (res.data.code == 1) {
            ElMessage({
              type: "success",
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                getList();
                dialogFormVisible.value = false;
              },
            });
          } else {
            ElMessage({
              type: "error",
              message: res.data.msg,
            });
          }
        });
      } else {
        goodsAddApi(form.value).then((res) => {
          if (res.data.code == 1) {
            ElMessage({
              type: "success",
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                getList();
                dialogFormVisible.value = false;
              },
            });
          } else {
            ElMessage({
              type: "error",
              message: res.data.msg,
            });
          }
        });
      }
    } else {
      ElMessage({
        type: "warning",
        message: "请填写完整信息",
      });
    }
  });
}
getList()
</script>

<style lang="scss" scoped>
.bigbox {
  display: flex;
  background-color: white;
  padding-top: 20px;
  margin-bottom: 20px;
  padding-left: 20px;
}

.tableData_image {
  width: 180px;
  height: 100px;
}

.bannerImage {
  width: 200px;
  height: 200px;
}

.el-pagination {
  margin-top: 20px;
}
</style>